package com.yzh.wanandroid.component.fragment

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.IntegralListAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentUserInfoBinding
import com.yzh.wanandroid.vm.UserInfoFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class UserInfoFragment : MvvmFragment<FragmentUserInfoBinding, UserInfoFragmentVm>() {

    private val TAG = "UserInfoFragment"

    override fun initViewModel(): UserInfoFragmentVm = createViewModel()

    override fun getLayoutId() = R.layout.fragment_user_info

    private val integralListAdapter by lazy { IntegralListAdapter() }

    override fun initView(view: View) {
        initRecyclerView()
        initTitleBar()
    }

    /**
     * 初始化RecyclerView
     */
    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(activity)
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            integralList.layoutManager = linearLayoutManager
            adapter = integralListAdapter
        }
    }

    /**
     * 初始化titleBar
     */
    private fun initTitleBar() {
        mBinding.run {
            userInfoTitleLayout.titleText.setText(R.string.integral_info)
            userInfoTitleLayout.toolbar.navigationIcon = requireActivity().getDrawable(R.drawable.arrow_back)
            userInfoTitleLayout.toolbar.setNavigationOnClickListener {
                requireActivity().onBackPressed()
            }
        }
    }

    override fun initData() {
        loadArticleData()
        showHeadText()
    }

    /**
     *  显示积分
     */
    private fun showHeadText() {
        mViewModel.mCoinCount.observe(this) {
            integralListAdapter.setHeadData(it.toString())
        }
    }

    private fun loadArticleData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData().collectLatest {
                    integralListAdapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}